﻿using BaseAuthRole.Domain.Input;
using BaseAuthRole.Domain.OutPut;
using BaseAuthRole.DTO.Role;
using BaseAuthRole.IService;
using BaseAuthRole.Service;
using BaseAuthRole.Web.Filters;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Org.BouncyCastle.Bcpg.Sig;
using RS.BaseModel.Common;
using System.Drawing.Printing;

namespace BaseAuthRole.Web.Api.Client
{
    /// <summary>
    /// 角色
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class RoleForClientController : ControllerBase
    {
        private IUserService _userService;
        public RoleForClientController(IUserService userService)
        {
            this._userService = userService;
        }

        /// <summary>
        /// 获取角色分页列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetRolePageList([FromQuery] GetRolePageListClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("role")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            var result = new CommonResult<PageModel<GetRolePageListClientOutPut>>();

            long count = 0;

            var condition = "";

            Dictionary<string, object> obj = new Dictionary<string, object>();


            if (!string.IsNullOrEmpty(input.Name))
            {
                obj.Add("para", $"%{input.Name}%");

                condition = " \"Name\" like @para";
            }
            var info = this._userService.GetRoles(input.Page, input.PageSize, condition, " \"CreateTime\" desc", out count, obj);

            var total_num = Math.Ceiling(count / (decimal)input.PageSize);

            //获取角色Id列表
            var roleIds = info.Select(p => p.Id).ToList();
            var roleProjectRelations = _userService.GetRoleProjectRelations(roleIds);

            result.IsError = false;
            result.Message = "获取成功";
            result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;
            result.Result = new PageModel<GetRolePageListClientOutPut>
            {
                Data = info.Select(p => new GetRolePageListClientOutPut
                {
                    Name = p.Name,
                    CreateTimeStr = p.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    Description = p.Description,
                    Id = p.Id,
                    UpdateTimeStr = p.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    Projects = roleProjectRelations.Where(x => x.RoleId == p.Id).Select(x => x.Project).ToList()
                }).ToList(),
                DataCount = count,
                Page = input.Page,
                PageCount = Convert.ToInt32(total_num),
                PageSize = input.PageSize,
            };

            return Ok(result);
        }

        /// <summary>
        /// 导出角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult ExportRole([FromQuery] ExportRoleClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("role")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            var result = _userService.ExportRole(input);
            if (result.IsError)
            {
                return Ok(new CommonResult { IsError = true, Message = result.Message, Value = result.Value });
            }
            else
            {
                return File(result.Result.MemoryStream, "application/octet-stream", result.Result.FileName);
            }
        }

        /// <summary>
        /// 获取角色详情
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetRoleDetail([FromQuery] GetRoleDetailClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("role")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            CommonResult<GetRoleDetailClientOutPut> result = new CommonResult<GetRoleDetailClientOutPut>();

            var role = this._userService.GetRole(input.RoleId);
            if (role == null)
            {
                result.IsError = true;
                result.Message = "角色不存在";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
            }

            result.Result = new GetRoleDetailClientOutPut
            {
                Id = role.Id,
                Name = role.Name,
                ActionTrees = new List<ActionTree>(),
                CreateTimeStr = role.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                Description = role.Description,
                UpdateTimeStr =role.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss")
            };

            var actions = this._userService.GetRoleAction(input.RoleId);

            var ActionGroup = this._userService.GetActionGroup();

            var data = new List<ActionTree>();

            foreach (var o in ActionGroup)
            {
                data.Add(new ActionTree
                {
                    id = o.Id,
                    parent = "#",
                    text = o.Name

                });

                foreach (var p in o.Actions)
                {
                    data.Add(new ActionTree
                    {
                        id= p.Id,
                        parent = o.Id,
                        text = p.ActionName,
                        state = new ActionTreeState
                        {
                            selected = actions.Any(m => m == p.Id)
                        }
                    });
                }
            }

            result.Result.ActionTrees = data;

            result.IsError = false;
            result.Message = "获取成功";
            result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;

            return Ok(result);
        }

        /// <summary>
        /// 添加角色详情
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpPost]
        public IActionResult AddRoleDetail([FromBody] AddRoleDetailClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("role")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            var result = new CommonResult();

            var name = input.Name;

            var des = input.Description;

            var data = input.Data;

            var actions = string.IsNullOrEmpty(data) ? new List<string>() : data.Split(',').ToList();

            var role = new Role
            {
                IsSystem = 0,
                Name = name,
                Description = des
            };

            var r = this._userService.CreateRoleAction(role, actions);

            if (r == -2)
            {
                result.IsError = true;
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
                result.Message = "角色名已存在";
                return Ok(result);
            }

            if (r > 0)
            {
                result.Message = "添加成功";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;
                result.IsError = false;
            }
            else
            {
                result.Message = "添加失败";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
                result.IsError = true;
            }

            return Ok(result);
        }

        /// <summary>
        /// 更新角色详情
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpPost]
        public IActionResult UpdateRoleDetail([FromBody] UpdateRoleDetailClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("role")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            var result = new CommonResult();

            var id = input.RoleId;

            var name = input.Name;

            var des = input.Description;

            var data = input.Data;

            var actions = string.IsNullOrEmpty(data) ? new List<string>() : data.Split(',').ToList();


            var role = this._userService.GetRole(id);

            if (role == null)
            {
                result.IsError = true;
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
                result.Message = "角色不存在";
                return Ok(result);
            }

            role.Name = name;
            role.Description = des;

            var r = this._userService.UpdateRoleAction(role, actions);

            if (r == -2)
            {
                result.IsError = true;
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
                result.Message = "角色名已存在";
                return Ok(result);
            }

            if (r > 0)
            {
                result.Message = "更新成功";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;
                result.IsError = false;
            }
            else
            {
                result.Message = "更新失败";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
                result.IsError = true;
            }


            return Ok(result);
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpPost]
        public IActionResult DelRole([FromBody] DelRoleClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("role")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            return Ok(_userService.DelRole(input.RoleId));
        }

        /// <summary>
        /// 获取角色关联项目
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetRoleRelateProject([FromQuery] GetRoleRelateProjectClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("role")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            CommonResult<List<RoleProjectRelation>> result = new CommonResult<List<RoleProjectRelation>>();

            var role = this._userService.GetRole(input.RoleId);

            if (role == null)
            {
                result.IsError = true;
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
                result.Message = "角色不存在";
                return Ok(result);
            }

            var roleProjectRelations = _userService.GetRoleProjectRelations(new List<string> { input.RoleId });

            result.IsError = false;
            result.Message = "获取成功";
            result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;
            result.Result = roleProjectRelations;

            return Ok(result);
        }

        /// <summary>
        /// 保存角色关联项目
        /// </summary>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpPost]
        public IActionResult SaveRoleRelateProject([FromBody] SaveRoleRelateProjectClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("role")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            return Ok(_userService.SaveRoleProjectRelations(input));
        }

        /// <summary>
        /// 获取角色基础信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetRole([FromQuery] GetRoleDetailClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("role")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            CommonResult<GetRoleDetailClientOutPut> result = new CommonResult<GetRoleDetailClientOutPut>();

            var role = this._userService.GetRole(input.RoleId);
            if (role == null)
            {
                result.IsError = true;
                result.Message = "角色不存在";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
            }

            result.Result = new GetRoleDetailClientOutPut
            {
                Id = role.Id,
                Name = role.Name,
                ActionTrees = new List<ActionTree>(),
                CreateTimeStr = role.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                Description = role.Description,
                UpdateTimeStr =role.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss")
            };

            result.IsError = false;
            result.Message = "获取成功";
            result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;

            return Ok(result);
        }

        /// <summary>
        /// 获取权限树列表信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetActionTreeList([FromQuery] GetActionTreeListClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("role")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            CommonResult<List<ActionTree>> result = new CommonResult<List<ActionTree>>();

            var ActionGroup = this._userService.GetActionGroup();

            var data = new List<ActionTree>();

            foreach (var o in ActionGroup)
            {
                data.Add(new ActionTree
                {
                    id = o.Id,
                    parent = "#",
                    text = o.Name

                });

                foreach (var p in o.Actions)
                {
                    data.Add(new ActionTree
                    {
                        id= p.Id,
                        parent = o.Id,
                        text = p.ActionName,
                        state = new ActionTreeState
                        {
                            selected = false
                        }
                    });
                }
            }

            result.Result = data;

            result.IsError = false;
            result.Message = "获取成功";
            result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;

            return Ok(result);
        }

        /// <summary>
        /// 获取角色用户分页列表
        /// </summary>
        /// <param name="input">输入信息</param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetRoleUserPageList([FromQuery] GetRoleUserPageListClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("role")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            var result = this._userService.GetRoleUserInfoList(input);
            //根据供应商处理手机号，身份证号
            foreach (var data in result.Result.Data)
            {
                data.IdCardNo = "";
                if (!(data.EmployeeType == "7" || data.EmployeeType == "98" || data.EmployeeType == "99" || data.EmployeeType == "101"))
                {
                    data.Phone = "";
                }
            }

            return Ok(result);
        }

        /// <summary>
        /// 添加角色用户
        /// </summary>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpPost]
        public IActionResult AddRoleUser([FromBody] AddRoleUserClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("role")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            return Ok(this._userService.AddRoleUser(input));
        }

        /// <summary>
        /// 删除角色用户
        /// </summary>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpPost]
        public IActionResult DelRoleUser([FromBody] DelRoleUserClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("role")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            return Ok(this._userService.DelRoleUser(input));
        }

        /// <summary>
        /// 导入角色用户
        /// </summary>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpPost]
        public IActionResult ImportRoleUser([FromForm] ImportRoleUserClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("role")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            return Ok(this._userService.ImportRoleUser(input));
        }

        /// <summary>
        /// 导出角色用户
        /// </summary>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult ExportRoleUser([FromQuery] ExportRoleUserClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("role")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            var result = _userService.ExportRoleUser(input);
            if (result.IsError)
            {
                return Ok(new CommonResult { IsError = true, Message = result.Message, Value = result.Value });
            }
            else
            {
                return File(result.Result.MemoryStream, "application/octet-stream", result.Result.FileName);
            }
        }

        /// <summary>
        /// 下载角色用户模板
        /// </summary>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult DownloadRoleUserTemplate([FromQuery] DownloadRoleUserTemplateClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("role")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            var result = _userService.DownloadRoleUserTemplate(input);
            if (result.IsError)
            {
                return Ok(new CommonResult { IsError = true, Message = result.Message, Value = result.Value });
            }
            else
            {
                return File(result.Result.MemoryStream, "application/octet-stream", result.Result.FileName);
            }
        }
    }
}
